package com.ibm.cps.sql.expression;

import java.util.HashSet;
import java.util.Set;

import com.ibm.util.exception.CPSException;

public class ArrayVisitingNode implements ValueExpression {
	private String valueFieldName;
	private int index;
	
	public ArrayVisitingNode() {
		//Only used for serialization
	}

	public ArrayVisitingNode(String valueFieldName, int index) {
		this.valueFieldName = valueFieldName;
		this.index = index;
	}

	public String getValueFieldName() {
		return valueFieldName;
	}

	public int getIndex() {
		return index;
	}
	
	public void setValueFieldName(String valueFieldName) {
		this.valueFieldName = valueFieldName;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	@Override
	public Set<String> collectVariableNames() {
		Set<String> result = new HashSet<>();
		result.add(valueFieldName);
		return result;
	}

	@Override
	public void updateVariableName(String original, String fullQualifiedName) {
		if(valueFieldName.equals(original))
			valueFieldName = fullQualifiedName;
	}

	@Override
	public Object evaluate(FieldEvaluator evaluator) throws CPSException {
		//Might be some illegal casting
		Object[] values = evaluator.evaluateasArray(valueFieldName);
		return (Comparable)values[index];
//		throw new CPSException(ErrorCode.NO_IMPLEMENTATION_CODE, "Evaluating on a ArrayVisitingNode is not supported by now");
	}

}
